﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk;

namespace XrmLibrary.MsCrm4Adapter.Extensions
{
    public static class DateTimeExtensions
    {
        public static CrmDateTime ToCrmDateTime(this DateTime dateTime)
        {
            CrmDateTime crmDateTime = new CrmDateTime
                                          {
                                              date = dateTime.ToShortDateString(),
                                              time = dateTime.ToShortTimeString()
                                          };
            TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
            string sOffset;
            if (offset.Hours < 0)
            {
                sOffset = "-" + (offset.Hours*-1).ToString().PadLeft(2, '0');
            }
            else
            {
                sOffset = "+" + offset.Hours.ToString().PadLeft(2, '0');
            }
            sOffset += offset.Minutes.ToString().PadLeft(2, '0');
            crmDateTime.Value = dateTime.ToString(string.Format("yyyy-MM-ddTHH:mm:ss{0}", sOffset));
            return crmDateTime;
        }
    }
}
